package com.atguigu.day2;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {

    /*
     * 可重入锁又名递归锁，是指在同一个线程中，外层方法获取锁的时候，在进入该线程的内部方法会自动获取锁。
     * JAVA中ReentrantLock和synchronized都是可重入锁，可重入锁的一个优点是可以一定程度上避免死锁。

     * */

    public synchronized void a() {
        this.b();
        System.out.println("a");
    }

    public synchronized void b() {
        System.out.println("b");
    }

    //ReentrantLock 版本演示可重入锁
    private final ReentrantLock lock = new ReentrantLock();

    public void c() {
        lock.lock();
        try {
//            this.d();
            lock.lock();
            try {
                System.out.println("d");
            } finally {
                lock.unlock();
            }

            System.out.println("c");
        } finally {
            lock.unlock();
        }
    }


    public void d() {
        lock.lock();
        try {
            System.out.println("d");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo reentrantLockDemo = new ReentrantLockDemo();
        reentrantLockDemo.a();
        reentrantLockDemo.c();
    }
}
